/**
 * 
 */
package com.elcom.emocbc.util;

import java.io.IOException;

import com.elcom.ipc_udp_msg.MSG_REQUEST;
import com.elcom.ipc_udp_msg.MSG_RESPONSE;
import com.elcom.ipc_udp_msg.MessageAnalyzerImpl;
import com.elcom.ipc_udp_msg.control.MSG_RELOAD_CONFIG;
import com.elcom.util.ipc.IPCHandler;

/**
 * @author tiamo114
 *
 */
public class SendReloadConfig {
	private IPCHandler ipc = null;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new SendReloadConfig().start(args[0], args[1]);
	}
	
	private MSG_RESPONSE syncRequest(IPCHandler ipc, String targetModule, MSG_REQUEST req, long wait_response_timeout) throws IOException {
	   System.out.println("Send Reload Config Request!!!"); 
		ipc.sentMessage(targetModule, req);

	    MSG_RESPONSE resp = null;
	    long sleep = 0;
	    while (sleep < wait_response_timeout && null == resp) {
	      long begin = System.currentTimeMillis();
	      try {
	        resp = (MSG_RESPONSE)ipc.getMessage();
	      }
	      catch (java.net.SocketTimeoutException ex) {}
	      catch (java.io.InterruptedIOException ex) {}
	      long end = System.currentTimeMillis();

	      sleep += (end - begin);
	    } //while

	    return resp;
	  }

	private void start(String ipcName, String index) {
		try {
			this.ipc = new IPCHandler(new MessageAnalyzerImpl(), ipcName);
		} catch (IOException e) {
			System.out.println("Exception init IPCHandler: " + e.getMessage());
		}
		
		try {
			MSG_RELOAD_CONFIG req = new MSG_RELOAD_CONFIG();
			req.routing_label.SOURCE_MODULE = ipcName;
			req.routing_label.DESTINATION_MODULE = "cellbroadcast"+index;
			
			syncRequest(this.ipc, "cellbroadcast"+index, req, 5000);
		}catch (Exception ex) {
			System.out.println("Exception when send IPC message and execute: "+ex.getMessage());
		}
	}
}
